package com.campus.secondhand.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.Product;
import com.campus.secondhand.entity.PurchaseRequest;
import com.campus.secondhand.entity.School;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.mapper.ProductMapper;
import com.campus.secondhand.mapper.PurchaseRequestMapper;
import com.campus.secondhand.mapper.SchoolMapper;
import com.campus.secondhand.mapper.UserMapper;
import com.campus.secondhand.service.ProductService;
import com.campus.secondhand.service.PurchaseRequestService;
import com.campus.secondhand.service.SchoolService;
import com.campus.secondhand.service.UserService;
import com.campus.secondhand.model.vo.ProductDetailVO;
import com.campus.secondhand.model.vo.ProductListVO;
import com.campus.secondhand.model.vo.PurchaseRequestDetailVO;
import com.campus.secondhand.model.vo.PurchaseRequestVO;
import com.campus.secondhand.model.vo.UserDetailVO;
import com.campus.secondhand.model.vo.UserInfoVO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 首页Banner控制器
 */
@RestController
@RequestMapping("/banners")
@RequiredArgsConstructor
@Slf4j
public class BannerController {

    private final ProductService productService;
    private final SchoolService schoolService;
    private final UserService userService;
    private final PurchaseRequestService purchaseRequestService;
    private final ProductMapper productMapper;
    private final SchoolMapper schoolMapper;
    private final UserMapper userMapper;
    private final PurchaseRequestMapper purchaseRequestMapper;


    /**
     * 获取首页Banner数据列表
     * 随机返回四种类型的数据：商品、求购信息、学校、用户
     *
     * @return Banner列表数据
     */
    @GetMapping("/list")
    public Result<List<Map<String, Object>>> list() {
        List<Map<String, Object>> bannerList = new ArrayList<>();

        try {
            // 1. 随机获取一个商品
            Result<ProductDetailVO> productResult = getRandomProduct();
            if (productResult.getCode() == 200 && productResult.getData() != null) {
                Map<String, Object> productBanner = new HashMap<>();
                productBanner.put("id", 1);
                productBanner.put("type", "product");
                productBanner.put("title", "热门商品推荐");
                productBanner.put("subtitle", "发现校园里的优质二手商品");
                productBanner.put("product", productResult.getData());
                productBanner.put("image", getFirstImageUrl(productResult.getData().getImageUrls()));
                productBanner.put("link", "/products/" + productResult.getData().getId());
                bannerList.add(productBanner);
            }

            // 2. 随机获取一个学校
            Result<School> schoolResult = getRandomSchool();
            if (schoolResult.getCode() == 200 && schoolResult.getData() != null) {
                School school = schoolResult.getData();
                Map<String, Object> schoolBanner = new HashMap<>();
                schoolBanner.put("id", 2);
                schoolBanner.put("type", "school");
                schoolBanner.put("title", "热门学校");
                schoolBanner.put("subtitle", "浏览来自各大高校的二手商品");

                Map<String, Object> schoolData = new HashMap<>();
                schoolData.put("id", school.getId());
                schoolData.put("name", school.getName());
                schoolData.put("logo", school.getLogo());
                schoolData.put("productCount", school.getProductCount());
                schoolData.put("percentage", 80); // 默认百分比值
                schoolData.put("color", "#409EFF"); // 默认颜色

                schoolBanner.put("school", schoolData);
                schoolBanner.put("image", school.getCover() != null ? school.getCover() : school.getLogo());
                schoolBanner.put("link", "/school/" + school.getId());
                bannerList.add(schoolBanner);
            }

            // 3. 随机获取一个用户
            Result<UserInfoVO> userResult = getRandomUser();
            if (userResult.getCode() == 200 && userResult.getData() != null) {
                UserInfoVO user = userResult.getData();
                Map<String, Object> userBanner = new HashMap<>();
                userBanner.put("id", 3);
                userBanner.put("type", "user");
                userBanner.put("title", "活跃卖家");
                userBanner.put("subtitle", "信誉良好的校园卖家");

                Map<String, Object> userData = new HashMap<>();
                userData.put("id", user.getId());
                userData.put("name", user.getNickname());
                userData.put("avatar", user.getAvatar());
                userData.put("school", user.getSchool());
                userData.put("credibility", user.getCredibility());
                userData.put("productCount", 10); // 默认值，实际项目中可以通过查询获取

                userBanner.put("user", userData);
                userBanner.put("image", "banner-user.jpg"); // 默认背景图
                userBanner.put("link", "/user/" + user.getId());
                bannerList.add(userBanner);
            }

            // 4. 随机获取一个求购信息
            Result<PurchaseRequestDetailVO> requestResult = getRandomPurchaseRequest();
            if (requestResult.getCode() == 200 && requestResult.getData() != null) {
                PurchaseRequestDetailVO request = requestResult.getData();
                Map<String, Object> requestBanner = new HashMap<>();
                requestBanner.put("id", 4);
                requestBanner.put("type", "request");
                requestBanner.put("title", "求购信息");
                requestBanner.put("subtitle", "查看校园里的求购需求");

                Map<String, Object> requestData = new HashMap<>();
                requestData.put("id", request.getId());
                requestData.put("title", request.getTitle());
                requestData.put("budget", request.getBudget());
                requestData.put("user", request.getUser());

                // 从用户的UserDetailVO获取学校信息
                if (request.getUser() != null) {
                    requestData.put("school", request.getUser().getSchool());
                } else {
                    requestData.put("school", "未知学校");
                }

                requestBanner.put("request", requestData);

                // 求购信息可能没有图片，使用默认图片
                requestBanner.put("image", "/assets/images/default-request.jpg");

                requestBanner.put("link", "/requests/" + request.getId());
                bannerList.add(requestBanner);
            }

            return Result.success(bannerList);
        } catch (Exception e) {
            log.error("获取Banner数据失败", e);
            // 即使出错也尽量返回一部分数据
            return Result.success(bannerList, "部分数据加载成功");
        }
    }

    /**
     * 随机获取一个商品
     */
    private Result<ProductDetailVO> getRandomProduct() {
        try {
            Long randomId = productMapper.selectOne(
                    new LambdaQueryWrapper<Product>()
                            .select(Product::getId)
                            .eq(Product::getStatus, 1) // 正常状态的商品
                            .last("ORDER BY RAND() LIMIT 1"))
                    .getId();
            return productService.getProductDetail(randomId, null);
        } catch (Exception e) {
            log.error("随机获取商品失败", e);
            return Result.error("获取商品数据失败");
        }
    }

    /**
     * 随机获取一个学校
     */
    private Result<School> getRandomSchool() {
        try {
            Long randomId = schoolMapper.selectOne(
                    new LambdaQueryWrapper<School>()
                            .select(School::getId)
                            .last("ORDER BY RAND() LIMIT 1"))
                    .getId();
            return Result.success(schoolService.getSchoolById(randomId).getData());
        } catch (Exception e) {
            log.error("随机获取学校失败", e);
            return Result.error("获取学校数据失败");
        }
    }

    /**
     * 随机获取一个用户
     */
    private Result<UserInfoVO> getRandomUser() {
        try {
            Long randomId = userMapper.selectOne(
                    new LambdaQueryWrapper<User>()
                            .select(User::getId)
                            .eq(User::getStatus, 1) // 正常状态的用户
                            .last("ORDER BY RAND() LIMIT 1"))
                    .getId();
            return userService.getUserInfo(randomId);
        } catch (Exception e) {
            log.error("随机获取用户失败", e);
            return Result.error("获取用户数据失败");
        }
    }

    /**
     * 随机获取一个求购信息
     */
    private Result<PurchaseRequestDetailVO> getRandomPurchaseRequest() {
        try {
            Long randomId = purchaseRequestMapper.selectOne(
                    new LambdaQueryWrapper<PurchaseRequest>()
                            .select(PurchaseRequest::getId)
                            .eq(PurchaseRequest::getIsActive, 1) // 有效的求购信息
                            .last("ORDER BY RAND() LIMIT 1"))
                    .getId();
            return purchaseRequestService.getRequestDetail(randomId);
        } catch (Exception e) {
            log.error("随机获取求购信息失败", e);
            return Result.error("获取求购数据失败");
        }
    }

    /**
     * 获取商品第一张图片作为封面
     */
    private String getFirstImageUrl(List<String> imageUrls) {
        if (imageUrls != null && !imageUrls.isEmpty()) {
            return imageUrls.get(0);
        }
        return "/assets/images/default-product.jpg"; // 默认图片
    }
}